import { Button, Upload, message as antdMessage } from "antd";
import React, { useState } from "react";
import { MyUpload } from "./components";
import { UploadChangeParam, UploadFile } from "antd/es/upload";
const App: React.FC = () => {
  // 上传之前钩子函数， 一般用来进行验证
  const beforeUpload = (file: File) => {
    // type: "image/webp"
    //       "image/jpeg"
    //       "image/png"
    if (!file.type.includes("image")) {
      antdMessage.error("上传只可以选择图片");
      return false;
    }
    // 单位： b
    // 1024b = 1kb
    // 1024kb = 1mb
    // 1024mb = 1gb
    // 1024gb = 1tb
    // 1024tb = 1
    console.log(file.size);
    if (file.size > 1 * 1024 * 1024) {
      antdMessage.error("图片不可以超过1MB");
      return false;
    }

    return true;
  };

  const [urls1, setUrls1] = useState<string[]>([]);
  const onChange = (result: any) => {
    console.log(result);
    setUrls1([...urls1, result.data.data.url]);
  };

  const [urls2, setUrls2] = useState<string[]>([]);

  const onChange1 = (e: UploadChangeParam<UploadFile<any>>) => {
    console.log(e);
    if(e.file.response) {
      const { url } = e.file.response.data
      setUrls2([...urls1, url])
    }
  };

  return (
    <div>
      {/* antd */}
      <h1>antd 上传</h1>
      <Upload
        beforeUpload={(e: File) => beforeUpload(e)}
        action="/api/upload"
        onChange={(e) => onChange1(e)}
      >
        <Button>上传</Button>
      </Upload>
      {urls2.map((v, i) => {
        return <img src={v} key={i} height={200} alt="" />;
      })}
      {/* 自定义 */}
      <h1>自定义 组件 上传</h1>
      <MyUpload
        beforeUpload={(e: File) => beforeUpload(e)}
        action="/api/upload"
        onChange={(result) => onChange(result)}
      >
        <Button>上传</Button>
      </MyUpload>
      {urls1.map((v, i) => {
        return <img src={v} key={i} height={200} alt="" />;
      })}
    </div>
  );
};

export default App;
